package org.i1510.joeone.controller;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.jxls.transformer.XLSTransformer;

import org.i1510.common.bean.PageBean;
import org.i1510.common.utils.ConfPropertiesUtils;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.i1510.joeone.dao.IJoeoneCodeDao;
import org.i1510.joeone.po.JoeSubj2Class;
import org.i1510.joeone.po.JoeoneCode;
import org.i1510.joeone.po.JoeoneConf;
import org.i1510.joeone.po.JoeoneVote;
import org.i1510.joeone.service.IJoeSubj2ClassService;
import org.i1510.joeone.service.IJoeoneCodeService;
import org.i1510.joeone.service.IJoeoneConfService;
import org.i1510.joeone.service.IJoeoneVoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/admin/joeoneCode")
public class JoeoneCodeController {
    private static final Logger logger = LoggerFactory.getLogger(JoeoneCodeController.class);
    @Autowired
    private IJoeoneCodeService iJoeoneCodeService;
    @Autowired
    private IJoeoneConfService iJoeoneConfService;
    @Autowired
    private IJoeoneVoteService iJoeoneVoteService;
    @Autowired
    private IJoeSubj2ClassService iJoeSubj2ClassService;
    @Autowired
    private IJoeoneCodeDao iJoeoneCodeDao;
    
    private ResultMapper mapper;
    
    /**
    *@Author Rambo
    *@Desc：投票信息
    *@param request
    *@param joeoneCode
    *@param pageBean
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2015年12月14日 下午1:10:27 
    */
    @RequestMapping(value = "/codeVote", method = RequestMethod.GET)
    @ResponseBody
    public String codeVote(HttpServletRequest request,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            JoeoneConf joeoneConf = iJoeoneConfService.findByDocStatus("10");//理论上docStatus = 10 最多只有一条
            if(null != joeoneConf ){
            	//设置当前启用的产品季信息
            	joeoneCode.setJconfId(joeoneConf.getDocId());
            	//找到当前短码信息
                List joeoneCodes = iJoeoneCodeService.getCodeVote(joeoneCode, pageBean, conditions);
                Map map = new HashMap();
                map.put("pageNo", pageBean.getPageNo());
                map.put("pageSize", pageBean.getPageSize());
                map.put("listData",joeoneCodes);
                
                mapperRtn = ResultMapper.generateSuccess();
                mapperRtn.appendResult("data", map);
                
            }else{
            	mapperRtn = ResultMapper.generateFailure();
            	mapperRtn.appendResult("message", "本次评审未开启!");
            }
            
            
            
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：下载统计结果
    *@param request
    *@param joeoneCode
    *@param pageBean
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2015年6月17日 上午10:49:44 
    */
    @RequestMapping(value = "/downloadStat", method = RequestMethod.GET)
    @ResponseBody
    public String downloadStat(HttpServletRequest request,HttpServletResponse response,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) 
    		throws Exception {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            JoeoneConf joeoneConf = iJoeoneConfService.findByDocStatus("10");//理论上docStatus = 10 最多只有一条
            if(null != joeoneConf ){
            	//设置当前启用的产品季信息
            	joeoneCode.setJconfId(joeoneConf.getDocId());
            	//找到当前短码信息
                List joeoneCodes = iJoeoneCodeService.getStat(joeoneCode, pageBean, conditions);
                Map map = new HashMap();
                map.put("pageNo", pageBean.getPageNo());
                map.put("pageSize", pageBean.getPageSize());
                map.put("listData",joeoneCodes);
                
                mapperRtn = ResultMapper.generateSuccess();
                mapperRtn.appendResult("data", map);
                		
//                String templateFileName = (new StringBuilder("")).append("/Users/rambo/tmpl1.xls").toString();
//        		String destFileName = (new StringBuilder("")).append("/Users/rambo/tmp.xls").toString();
        		
//        		String templateFileName = (new StringBuilder("")).append("D:/ipad4joeone/tmpl1.xls").toString();
//        		String destFileName = (new StringBuilder("")).append("D:/ipad4joeone/tmp.xls").toString();

                
        		String templateFileName = (new StringBuilder("")).append(request.getSession().getServletContext().getRealPath("/")+"joeone/ipad/tmpl1.xls").toString();
        		String destFileName = (new StringBuilder("")).append(request.getSession().getServletContext().getRealPath("/")+"joeone/ipad/tmp.xls").toString();
        		
        		Map beans = new HashMap();

        		beans.put("list", joeoneCodes);
        		beans.put("jsubjectName", request.getParameter("jsubjectName"));
        		beans.put("jclassName", request.getParameter("jclassName"));
        		XLSTransformer transformer = new XLSTransformer();
        		try {
        			transformer.transformXLS(templateFileName, beans, destFileName);
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
        		FileInputStream is = new FileInputStream(destFileName);
        		response.setContentType("application/x-msdownload");
        		response.setHeader("Content-Disposition", "attachment; filename="
        				+ "out.xls");
        		OutputStream outputStream = response.getOutputStream();
        		byte[] buffer = new byte[1024];
        		int i = -1;
        		while ((i = is.read(buffer)) != -1) {
        			outputStream.write(buffer, 0, i);
        		}
        		outputStream.flush();
        		outputStream.close();
        		is.close();
        		return null;
        		
        		
                
            }else{
            	mapperRtn = ResultMapper.generateFailure();
            	mapperRtn.appendResult("message", "本次评审未开启!");
            }
            
            
            
        }        
        return null;
    }
    /**
    *@Author Rambo
    *@Desc：查看统计信息
    *@param request
    *@param joeoneCode
    *@param pageBean
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2015年6月17日 上午9:30:12 
    */
    @RequestMapping(value = "/viewStat", method = RequestMethod.GET)
    @ResponseBody
    public String viewStat(HttpServletRequest request,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            JoeoneConf joeoneConf = iJoeoneConfService.findByDocStatus("10");//理论上docStatus = 10 最多只有一条
            if(null != joeoneConf ){
            	//设置当前启用的产品季信息
            	joeoneCode.setJconfId(joeoneConf.getDocId());
            	//找到当前短码信息
                List joeoneCodes = iJoeoneCodeService.getStat(joeoneCode, pageBean, conditions);
                Map map = new HashMap();
                map.put("pageNo", pageBean.getPageNo());
                map.put("pageSize", pageBean.getPageSize());
                map.put("listData",joeoneCodes);
                //获取规划数
                JoeSubj2Class joeSubj2Class = iJoeSubj2ClassService.findBySubj2Class(joeoneCode.getJsubjectId(), joeoneCode.getJclassId());
                if(null != joeSubj2Class){
                    map.put("ghNum",joeSubj2Class.getGhNum());
                }else{
                    map.put("ghNum","0");
                }
                
                mapperRtn = ResultMapper.generateSuccess();
                mapperRtn.appendResult("data", map);
                
            }else{
            	mapperRtn = ResultMapper.generateFailure();
            	mapperRtn.appendResult("message", "本次评审未开启!");
            }
            
            
            
        }        
        return mapperRtn.toJson();
    }
    @RequestMapping(value = "/viewX", method = RequestMethod.GET)
    @ResponseBody
    public String viewX(HttpServletRequest request,@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            JoeoneConf joeoneConf = iJoeoneConfService.findByDocStatus("10");//理论上docStatus = 10 最多只有一条
            if(null != joeoneConf ){
            	//设置当前启用的产品季信息
            	joeoneCode.setJconfId(joeoneConf.getDocId());
            	//找到当前选择短码信息
                List joeoneCodes = iJoeoneCodeService.getViewX(joeoneCode,conditions);
                if(joeoneCodes.size() == 1){
                	mapperRtn = ResultMapper.generateSuccess();
                	Map code = (Map)joeoneCodes.get(0);
                    mapperRtn.appendResult("data", code);
                    //找到当前用户的投票数据
                    JoeoneVote joeoneVote = iJoeoneVoteService.findByUserAndCode(UserUtils.getSessionUserBean(request).getSysUser().getDocId(), code.get("docId").toString());
                    mapperRtn.appendResult("joeoneVote", joeoneVote);
                }else{
                	mapperRtn = ResultMapper.generateFailure();
                	mapperRtn.appendResult("message", "该短码["+joeoneCode.getJcode()+"]找不到,请重试!");
                }
            }else{
            	mapperRtn = ResultMapper.generateFailure();
            	mapperRtn.appendResult("message", "本次评审未开启!");
            }
            
            
            
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：保存对象
    *@param joeoneCode
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2013-11-15 下午4:20:56 
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpServletRequest request,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            joeoneCode.setDocStatus("10");
            mapper = iJoeoneCodeService.save(joeoneCode,request);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：删除对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2014-9-2 下午3:38:17 
    */
    @RequestMapping(value = "/deleteX", method = RequestMethod.POST)
    @ResponseBody
    public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            mapper = iJoeoneCodeService.delete(docId);
        }
        
        return mapper.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：查看对象
    *@param docId
    *@param errors
    *@return TODO
    *@Version  JoeoneCodeController.java,v 1.1 2014-9-2 下午3:39:35 
    */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            JoeoneCode joeoneCode = iJoeoneCodeService.findById(docId);
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", joeoneCode);
        }        
        return mapperRtn.toJson();
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("joeoneCode") JoeoneCode joeoneCode,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
        ResultMapper mapperRtn = ResultMapper.generateFailure();
        if(errors.hasErrors()){            
            mapperRtn = WebUtils.getMapper4Errors(errors);
        }else{
            Map conditions = new HashMap();
            conditions.put("fromDate", fromDate);
            conditions.put("toDate", toDate);
            List  joeoneCodes = iJoeoneCodeService.getPage(joeoneCode, pageBean,conditions);
            int totalCount =  iJoeoneCodeService.getPageCount(joeoneCode,conditions);
            Map map = new HashMap();
            map.put("pageNo", pageBean.getPageNo());
            map.put("pageSize", pageBean.getPageSize());
            map.put("totalCount", totalCount);
            map.put("listData",joeoneCodes);
            
            mapperRtn = ResultMapper.generateSuccess();
            mapperRtn.appendResult("data", map);
        }        
        return mapperRtn.toJson();
    }
    /**
    *@Author Rambo
    *@Desc：状态修改
    *@param request
    *@param docId
    *@param docStatus
    *@param errors
    *@return TODO
    *@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
    */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
        
        if(errors.hasErrors()){            
            mapper = WebUtils.getMapper4Errors(errors);
        }else{
            if(!StringUtils.isStringEmpty(docId)){
                JoeoneCode joeoneCode = new JoeoneCode();
                
                joeoneCode.setDocId(docId);
                joeoneCode.setDocStatus(docStatus);
                mapper = iJoeoneCodeService.save(joeoneCode,request);
            }else{
                mapper = ResultMapper.generateFailure();
                mapper.appendResult("messages", "无法找到该ID!");
            }
            
        }
        
        return mapper.toJson();
    }
}